#! /usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import time
import datetime
import requests

import global_var

"""
板坯计算
"""
log = global_var.gl_log

model_type = [
        "prediction",
        "optimization"
    ]

MODEL_VER = 2

class CFlattenModel:

    
    global MODEL_VER

    def __init__(self):
        pass

    def calc_model(self, plate_info, para_ext = {"type":1}):
        
        if MODEL_VER==1:
            return self.calc_modelv1(plate_info, para_ext)
        elif MODEL_VER==2:
            #log.info("MODEL_VER={}".format(MODEL_VER))
            return self.calc_modelv2(plate_info, para_ext)

        return None

    #type=0, prediction type=1, optimization
    def calc_modelv1(self, plate_info,para_ext):
        log.info("use modelv1")
        
        if plate_info==None:
            return dict({})

        str_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        type = para_ext["type"]
        log.info("modelv1, type={}".format(type))
        input_json ='{"data": {"_id":"%s","plate_id":"%s", "material_id":"%s", "steel grade":"%s", "plate length":%d, "plate width":%d, \
 "plate thickness":%0.2f, "yield point":%d, "tensile strength":%d, "plate act temperature":%0.2f, \
"Leverler inlet manual":%0.2f, "Leverler outlet manual":%0.2f, "Leverler flexion manual":%0.2f}, "mode": "%s" }' %(
                      str_now,
                      plate_info["plate_id"],
                      plate_info["material_id"], 
                      plate_info["steel grade"],  
                      plate_info["plate length"],
                      plate_info["plate width"], 
                      plate_info["plate thickness"],
                      plate_info["yield point"],
                      plate_info["tensile strength"],
                      plate_info["plate act temperature"],
                      plate_info["Leverler inlet manual"],
                      plate_info["Leverler outlet manual"],
                      plate_info["Leverler flexion manual"],
                      model_type[type]
                     )

        #print("model data: ", input_json)
        #const
        #log.info("modelcalc(type={}): plate [{}] act temp: {:03f}".format(type,plate_info["plate_id"], plate_info["plate act temperature"]))
        url = 'http://101.37.106.238/dt_ng_1521393261600496/industry/industry_brain/gerry_test_leveller_test_1_leveller_prediction_1_1/-1/predict'
        try:
            response = requests.post(url, json=input_json)
            #print("out result: ", response.json())
            if response.status_code==200:
                if type==1:
                    log.info("\n*** model1 calc ***\n<<<input>>>\n{}\n\n<<<output>>>\n{}\n".format(input_json,response.json()))
                return response.json()
            else:
                log.error("model calc err: [{}]".format(plate_info["plate_id"]))
                return dict({})
        except Exception as e:
            print("model err: ", e)
            return dict({})


    def calc_modelv2(self, plate_info, para_ext):
        log.info("use modelv2")
        """
        input_data='{"data":{"_id":"2019-10-2506:01:00","plate_id":112902864901,"material_id":1169008036,"steel
                grade":"BS960E","platelength":11550,"platewidth":1450,"platethickness":8.08,"yieldpoint":960,"tensile
                strength":980,"plateacttemperature":114.1855,"RULER_1M_CROSS":3,"RULER_1M_LENGTH":3,"Leverlerinlet
                manual":-3.0,"Leverleroutletmanual":4.0,"Leverlerflexionmanual":2.0},"mode":"optimization",
                "option1":2,"option2":1,"thickness":0.1,"yield_p":50,"temperature":40,"width":100,"time_factor":0.2
        """
        if plate_info==None:
            log.info("plate info is null")
            return dict({})
        
        def_para = {
                "option1":2,
                "option2":1,
                "thickness":0.5,
                "yield_p":50,
                "temperature":50,
                "width":100,
                "time_factor":0.2
            }
        
        for key in def_para:
            
            #if para_ext.has_key(key):
            if key in para_ext:
        
                pass
            else:
                para_ext[key] = def_para[key] 
    
        
        type = para_ext["type"]
        str_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        model_param = para_ext.copy()
        model_param.pop("type")
            
        if len(model_param):
            str_param = ", {}".format(str(model_param).replace("\'","\"").replace("{","").replace("}",""))
        else:
            str_param = ""

        input_json ='{"data": {"_id":"%s","plate_id":"%s", "material_id":"%s", "steel grade":"%s", "plate length":%d, "plate width":%d, \
    "plate thickness":%0.2f, "yield point":%d, "tensile strength":%d, "plate act temperature":%0.2f, \
    "Leverler inlet manual":%0.2f, "RULER_1M_CROSS":%0.1f,"RULER_1M_LENGTH":%0.1f,"Leverler outlet manual":%0.2f, "Leverler flexion manual":%0.2f}, "mode": "%s"%s }' %(
                        str_now,
                        plate_info["plate_id"],
                        plate_info["material_id"],
                        plate_info["steel grade"],
                        plate_info["plate length"],
                        plate_info["plate width"],
                        plate_info["plate thickness"],
                        plate_info["yield point"],
                        plate_info["tensile strength"],
                        plate_info["plate act temperature"],
                        plate_info["RULER_1M_CROSS"],
                        plate_info["RULER_1M_LENGTH"],
                        plate_info["Leverler inlet manual"],
                        plate_info["Leverler outlet manual"],
                        plate_info["Leverler flexion manual"],
                        model_type[type],
                        str_param
                        )
        
            #print("model data: ", input_json)
            #const
            #log.info("modelcalc(type={}): plate [{}] act temp: {:03f}".format(type,plate_info["plate_id"], plate_info["plate act temperature"]))
            #url for model v1
            #url = 'http://101.37.106.238/dt_ng_1521393261600496/industry/industry_brain/gerry_test_leveller_test_1_leveller_prediction_1_1/-1/predict'
            #url for model v2
        url = 'http://101.37.106.238/dt_ng_1521393261600496/industry/industry_brain/gerry_test_leveller_test_2_leveller_prediction_2_1/-1/predict'

        try:
            response = requests.post(url, json=input_json)
                #print("out result: ", response.json())
            if response.status_code==200:
                if type==1:
                    log.info("\n*** model2 calc ***\n<<<input>>>\n{}\n\n<<<output>>>\n{}\n".format(input_json,response.json()))
                return response.json()
            else:
                log.error("model calc err: [{}]".format(plate_info["plate_id"]))
                return dict({})
        except Exception as e:
            print("model err: ", e)
            return dict({})

def test():
    model = CFlattenModel()
    plate_info={}
    plate_info["plate_id"]="112903129901"
    plate_info["material_id"]="1129031299" 
    plate_info["steel grade"]="BW400"
    plate_info["plate length"]=10000
    plate_info["plate width"]=1805
    plate_info["plate thickness"]=5.27
    plate_info["yield point"]=960
    plate_info["tensile strength"]=1250
    plate_info["plate act temperature"]=30
    plate_info["Leverler inlet manual"]=-2.3
    plate_info["Leverler outlet manual"]=3.0
    plate_info["Leverler flexion manual"]=2.0

    model.calc_modelv1(plate_info,type=0)
    #print('data:\{ "length":{}\}'.format(30))
if __name__=="__main__":
    test()